// Copyright (c) 2014-present, b3log.org
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package file

import (
	"encoding/json"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	"chainmaker.org/chainmaker/smarteditor/session"

	"chainmaker.org/chainmaker/smarteditor/util"

	"github.com/88250/gulu"
)

// GetZipHandler handles request of retrieving zip file.
func GetZipHandler(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	path := q["path"][0]

	if ".zip" != filepath.Ext(path) {
		http.Error(w, "Bad Request", 400)
		return
	}

	if !gulu.File.IsExist(path) {
		http.Error(w, "Not Found", 404)
		return
	}

	filename := filepath.Base(path)

	w.Header().Set("Content-Disposition", "attachment; filename="+filename)
	w.Header().Set("Content-Type", "application/zip")
	http.ServeFile(w, r, path)

	err := os.Remove(path)
	if err != nil {
		log.Warnf("remove file failed, err:%v", err)
	}
}

// CreateZipHandler handles request of creating zip.
func CreateZipHandler(w http.ResponseWriter, r *http.Request) {
	data := gulu.Ret.NewResult()
	defer gulu.Ret.RetResult(w, r, data)

	var args map[string]interface{}
	if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
		log.Errorf("CreateZipHandler decode args failed, err:%s", err)
		data.Code = -1
		return
	}

	path := args["path"].(string)
	var name string
	needDeleteFile := false
	base := filepath.Base(path)
	if nil != args["name"] {
		needDeleteFile = true
		name = args["name"].(string)
	} else {
		name = base
	}

	dir := filepath.Dir(path)
	if !gulu.File.IsExist(path) {
		data.Code = -1
		data.Msg = "Can't find file [" + path + "]"
		return
	}

	zipOriginalFilePath := filepath.Join(dir, name)
	zipFile, err := gulu.Zip.Create(zipOriginalFilePath + ".zip")
	if nil != err {
		log.Errorf("create zip file failed, err:%v", err)
		data.Code = -1
		return
	}
	defer util.CloseAndLogError(zipFile)

	if gulu.File.IsDir(path) {
		err := zipFile.AddDirectory(base, path)
		if err != nil {
			log.Errorf("create zip file, add directory failed, err:%v", err)
			data.Code = -1
			return
		}
	} else {
		err := zipFile.AddEntry(base, path)
		if err != nil {
			log.Errorf("create zip file, add entry failed, err:%v", err)
			data.Code = -1
			return
		}
	}

	data.Data = zipOriginalFilePath

	if needDeleteFile {
		go func() {
			err = os.Remove(path)
			if err != nil {
				log.Errorf("CreateZipHandler remove original file")
			}
		}()
	}
}

// Get7zHandler handles request of retrieving 7z file.
func Get7zHandler(w http.ResponseWriter, r *http.Request) {
	uid, err := session.GetUidFromSession(r)
	if err != nil {
		http.Error(w, "Forbidden", http.StatusForbidden)
		return
	}
	q := r.URL.Query()
	path := q["path"][0]

	// if ".7z" != filepath.Ext(path) {
	// 	http.Error(w, "Bad Request", 400)
	// 	return
	// }

	if !gulu.File.IsExist(path) {
		http.Error(w, "Not Found", 404)
		return
	}
	// 校验是否有权限获取该文件
	if !session.CanAccess(uid, path) {
		http.Error(w, "Forbidden", http.StatusForbidden)
		return
	}
	filename := filepath.Base(path)
	w.Header().Set("Content-Disposition", "attachment; filename="+filename)
	if strings.HasSuffix(path, ".7z") {
		w.Header().Set("Content-Type", "application/7z")
	}

	http.ServeFile(w, r, path)
}

//Get7z export 7z file
func GetContractFile(w http.ResponseWriter, r *http.Request) {
	uid, err := session.GetUidFromSession(r)
	if err != nil {
		log.Warnf("[Get7z] access forbidden. err:%s", err)
		http.Error(w, "Forbidden", http.StatusForbidden)
		return
	}

	q := r.URL.Query()
	path := q["path"][0]
	if !session.CanAccess(uid, path) {
		log.Warnf("[Get7z] access forbidden. err:%s", err)
		http.Error(w, "Forbidden", http.StatusForbidden)
		return
	}

	if Suffix7Z != filepath.Ext(path) {
		log.Warnf("[Get7z] bad request")
		http.Error(w, "Bad Request", http.StatusBadRequest)
		return
	}

	if !util.FileExists(path) {
		log.Warnf("[Get7z] not found")
		http.Error(w, "Not Found", http.StatusBadRequest)
		return
	}

	filename := filepath.Base(path)
	w.Header().Set("Content-Disposition", "attachment; filename="+filename)
	w.Header().Set("Content-Type", "application/7z")
	http.ServeFile(w, r, path)
}

// Create7zHandler handles request of creating 7z
func Create7zHandler(w http.ResponseWriter, r *http.Request) {

	data := gulu.Ret.NewResult()
	defer gulu.Ret.RetResult(w, r, data)

	var args map[string]interface{}
	if err := json.NewDecoder(r.Body).Decode(&args); err != nil {
		log.Errorf("Create7zHandler decode args failed, err:%s", err)
		data.Code = -1
		return
	}

	path := args["path"].(string)
	var name string
	needDeleteFile := false
	base := filepath.Base(path)
	if nil != args["name"] {
		needDeleteFile = true
		name = args["name"].(string)
	} else {
		name = base
	}

	dir := filepath.Dir(path)
	if !gulu.File.IsExist(path) {
		data.Code = -1
		data.Msg = "Can't find file [" + path + "]"
		return
	}

	// 判断path是否为目录,还是文件
	isDir := gulu.File.IsDir(path)
	if !isDir {
		data.Data = path
		return
	}
	util.RemoveAllNoContractFiles(path)

	fileName := name + ".7z"
	os.RemoveAll(filepath.Join(dir, fileName))
	command := exec.Command("7z", "a", fileName, base)
	command.Dir = dir
	err := command.Run()
	if err != nil {
		log.Errorf("Create7zHandler cmd start error. err:%s", err)
	}
	// command2 := exec.Command("7z", "d", fileName, name+"/"+name)
	// command2.Dir = dir
	// err2 := command2.Run()
	// if err2 != nil {
	// 	log.Errorf("Create7zHandler cmd 7z d %s ,%s ,failed %s", fileName, name+"/"+name, err2.Error())
	// }

	data.Data = filepath.Join(dir, fileName)
	if needDeleteFile {
		go func() {
			//err = os.Remove(path)
			if err != nil {
				log.Errorf("CreateZipHandler remove original file")
			}
		}()
	}
}
